<template>
  <div class="account">
    <h2>用户信息管理</h2>
    <div class="search-container">
      <el-input class="el-input" v-model="searchQuery" placeholder="输入用户名搜索" @keyup.enter="searchUsers"></el-input>
      <el-button class="el-button search" @click="searchUsers">
        <img src="../../assets/img/search.png" alt="">
        筛选</el-button>
      <el-button class="el-button add" @click="openAddDialog">
        <img src="../../assets/img/add.png" alt="">
        新增用户</el-button>
      <el-table :data="currentUsers" stripe ref="userTable" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="UserId" label="用户id"></el-table-column>
        <el-table-column label="用户信息" width="160">
          <template slot-scope="scope">
            <img :src="scope.row.Avatarurl" alt="" style="width: 30px; height: 30px; border-radius: 50%;">
            <span style="margin-left: 5px;">{{ scope.row.UserName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="联系方式" width="180">
          <template slot-scope="scope">
            <p style="margin-left: 5px">{{ scope.row.email }}</p>
            <p style="margin-left: 5px">{{ scope.row.Phone }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="password" label="密码" width="180">
            <template slot-scope="scope">
              <div style="padding-right: 30px;">
                <p style="display: -webkit-box; -webkit-line-clamp: 2;  -webkit-box-orient: vertical; overflow: hidden;  text-overflow: ellipsis;">{{ scope.row.password }}</p>
              </div>
            </template>
          </el-table-column>
        <el-table-column prop="IDcard" label="学生id" width="180"></el-table-column>
        <el-table-column prop="RegisterTime" label="注册时间" width="150">
          <template slot-scope="scope">
            <p>{{ formatTime(scope.row.RegisterTime) }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="State" label="状态">
          <template slot-scope="scope">
            <span :style="{
              backgroundColor: getStateColor(scope.row.State),
              color: getStateTextColor(scope.row.State),
              padding: '3px 5px', borderRadius: '3px'
            }">
              {{ scope.row.State }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <img src="../../assets/img/write.png" style="width: 20px; height: 25px; margin-right: 15px;" type="primary"
              @click="openEditDialog(scope.row)">
            <img src="../../assets/img/remove.png" style="width: 30px; height: 25px;" type="danger"
              @click="openDeleteDialog(scope.row)">
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="totalUsers">
      </el-pagination>
    </div>

    <!-- 删除确认弹窗 -->
    <el-dialog :visible.sync="deleteDialogVisible" title="删除用户">
      <p>确定要删除用户{{ currentDeleteUser.UserName }} 吗？此操作不可恢复。</p>
      <span style="margin-top: 30px;display: block;">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">删除</el-button>
      </span>
    </el-dialog>

    <!-- 新增用户信息弹窗 -->
    <el-dialog :visible.sync="addDialogVisible" title="新增用户">
      <el-form :model="newUser" :rules="rules" ref="addForm" label-width="80px">
        <el-form-item label="UserId" prop="UserId">
          <el-input v-model="newUser.UserId"></el-input>
        </el-form-item>
        <el-form-item label="用户头像" prop="Avatarurl">
          <img :src="newUser.Avatarurl || 'http://127.0.0.1:3000/head/moren/i.png'" alt="">
          <form class="uploadForm" enctype="multipart/form-data">
            <input type="file" name="image" placeholder="更换头像" class="img">
            <button type="button" class="btn" @click="sendImage">完成</button>
          </form>
        </el-form-item>
        <el-form-item label="用户名称" prop="UserName">
          <el-input v-model="newUser.UserName"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="Phone">
          <el-input v-model="newUser.Phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="newUser.email"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="newUser.password"></el-input>
        </el-form-item>
        <el-form-item label="学生id" prop="IDcard">
          <el-input v-model="newUser.IDcard"></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="State">
          <el-select v-model="newUser.State" placeholder="请选择状态">
            <el-option label="活跃" value="活跃"></el-option>
            <el-option label="禁用" value="禁用"></el-option>
            <el-option label="沉睡" value="沉睡"></el-option>
            <el-option label="流失" value="流失"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span style="margin: 30px 40px;display: block;">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAdd"></el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息弹窗 -->
    <el-dialog :visible.sync="editDialogVisible" title="修改用户">
      <el-form :model="currentEditUser" :rules="rules" ref="editForm" label-width="80px">
        <el-form-item label="用户名称" prop="UserName">
          <el-input v-model="currentEditUser.UserName"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="Phone">
          <el-input v-model="currentEditUser.Phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="currentEditUser.email"></el-input>
        </el-form-item>
        <el-form-item label="学生id" prop="IDcard">
          <el-input v-model="currentEditUser.IDcard"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="State">
          <el-select v-model="currentEditUser.State" placeholder="请选择状态">
            <el-option label="活跃" value="活跃"></el-option>
            <el-option label="禁用" value="禁用"></el-option>
            <el-option label="沉睡" value="沉睡"></el-option>
            <el-option label="流失" value="流失"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span style="margin: 30px 40px;display: block;">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEdit">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui';
import axios from 'axios';
import jq from "jquery"
import AjaxObj from "../../utils/jqAjaxUrl";
export default {
  data() {
    const validateemail = (rule, value, callback) => {
      const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (emailRegex.test(value)) {
        callback();
      } else {
        callback(new Error('请输入正确的邮箱格式'));
      }
    };

    const validatePhone = (rule, value, callback) => {
      const PhoneRegex = /^1[3-9]\d{9}$/;
      if (PhoneRegex.test(value)) {
        callback();
      } else {
        callback(new Error('请输入正确的手机号格式'));
      }
    };

    const validateIdCard = (rule, value, callback) => {
      if (value.length === 13) {
        callback();
      } else {
        callback(new Error('学生ID编号长度必须为13位'));
      }
    };
    const validatepassword = (rule, value, callback) => {
      if (value.length >= 6 && value.length <= 12) {
        callback();
      } else {
        callback(new Error('账号密码长度必须为6到12位'));
      }
    };

    return {
      users: [],
      // 搜索关键词
      searchQuery: '',
      // 当前页码
      currentPage: 1,
      // 每页显示数量
      pageSize: 10,
      // 总用户数
      totalUsers: 0,
      // 选中的用户列表
      selectedUsers: [],
      // 删除确认弹窗是否显示
      deleteDialogVisible: false,
      // 当前要删除的用户
      currentDeleteUser: {},
      // 用户信息弹窗是否显示
      addDialogVisible: false,
      // 用户信息
      newUser: {
        UserId: null,
        Avatarurl: '',
        UserName: '',
        email: '',
        password: '',
        IDcard: '',
        Phone: '',
        Sex: '',
        like: '',
        RegisterTime: new Date().toLocaleString(),
        State: '活跃'
      },
      // 编辑用户信息弹窗是否显示
      editDialogVisible: false,
      // 当前要编辑的用户
      currentEditUser: {},
      // 表单验证规则
      rules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateemail, trigger: 'blur' }
        ],
        Phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        IDcard: [
          { required: true, message: '请输入学生 ID', trigger: 'blur' },
          { validator: validateIdCard, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入学生 ID', trigger: 'blur' },
          { validator: validatepassword, trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    // 计算当前页的用户数据
    currentUsers() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      // 使用 (user.UserName || '') 确保为字符串，避免 null/undefined 报错
      const filteredUsers = this.users.filter(user =>
        (user.UserName || '').includes(this.searchQuery)
      );
      return filteredUsers.slice(start, end);
    }
  },
  mounted() {
    this.fetchUsers();
  },
  methods: {
    sendImage() {
            let _this = this;
            const formData = new FormData();
            formData.append('image', document.querySelector('input[name="image"]').files[0]);
            formData.append('email', _this.newUser.email); // 添加 email 参数
            jq.ajax({
                type: "post",
                url: AjaxObj.url + "/sendImg",
                data: formData,
                processData: false,                // jQuery不要去处理发送的数据
                contentType: false,                // jQuery不要去设置Content-Type请求头
                success(res) {
                    console.log("发送成功" + res);
                    console.log('发送成功')
                    if (res.status === 200 && res.data && res.data.Avatarurl) {
                        _this.newUser.Avatarurl = res.data.Avatarurl;
                    }
                },
                error(err) {
                    console.log("发送失败" + err);
                }
            });
        },
    formatTime(timeStr) {
      if (!timeStr) return '';
      const date = new Date(timeStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    async fetchUsers(page = 1, pageSize = 10, searchQuery = '') {
      try {
        const response = await axios.get('http://127.0.0.1:3000/usermess', {
          params: { page, pageSize, searchQuery }
        });
        // 根据实际响应结构赋值
        console.log('response.data', response.data)
        this.users = response.data.data; // 取响应中的 data 数组
        console.log('this.users', this.users)
        this.totalUsers = response.data.data.length; // 总数量用数组长度
      } catch (error) {
        console.error('获取用户数据失败:', error);
        Message.error('获取用户数据失败');
      }
    },
    // 搜索用户
    async searchUsers() {
      this.currentPage = 1;
      await this.fetchUsers(this.currentPage, this.pageSize, this.searchQuery);
    },
    // 修改分页处理方法
    async handleSizeChange(newSize) {
      this.pageSize = newSize;
      await this.fetchUsers(this.currentPage, this.pageSize, this.searchQuery);
    },
    async handleCurrentChange(newPage) {
      this.currentPage = newPage;
      await this.fetchUsers(this.currentPage, this.pageSize, this.searchQuery);
    },

    // 打开删除确认弹窗
    openDeleteDialog(user) {
      this.currentDeleteUser = user;
      this.deleteDialogVisible = true;
    },
    // 修改删除方法
    confirmDelete() {
      let _this = this;
      jq.ajax({
        type: 'delete',
        url: `http://127.0.0.1:3000/userdel/${this.currentDeleteUser.UserId}`, // 传递 id 到后端
        success(res) {
          if (res.status === 200) {
            _this.fetchUsers(_this.currentPage, _this.pageSize, _this.searchQuery);
            _this.deleteDialogVisible = false;
            Message.success(`删除用户 ${_this.currentDeleteUser.UserName} 成功`);
          } else {
            Message.error('删除失败');
          }
        },
        error(err) {
          console.error('删除失败:', err);
          Message.error('删除失败');
        }
      });
    },

    // 打开编辑用户信息弹窗
    openEditDialog(user) {
      this.currentEditUser = { ...user };
      this.editDialogVisible = true;
    },
    // 打开用户信息弹窗
    openAddDialog() {
      this.newUser = {
        UserId: this.generateNewId(),
        Avatarurl: '',
        password: '',
        UserName: '',
        email: '',
        IDcard: '',
        Phone: '',
        Sex: '',
        like: '',
        RegisterTime: new Date().toLocaleString(),
        State: '活跃'
      };
      this.addDialogVisible = true;
    },
    // 修改编辑方法
    confirmEdit() {
      let _this = this;
      jq.ajax({
        type: 'put',
        url: `http://127.0.0.1:3000/userfix`,
        data: this.currentEditUser,
        success(res) {
          if (res.status === 200) {
            _this.fetchUsers(_this.currentPage, _this.pageSize, _this.searchQuery);
            _this.editDialogVisible = false;
            Message.success(`修改用户 ${_this.currentEditUser.UserName} 成功`);
          } else {
            Message.error('修改失败');
          }
        },
        error(err) {
          console.error('修改失败:', err);
          Message.error('修改失败');
        }
      });
    },
    // 修改方法
    confirmAdd() {
      let _this = this;
      jq.ajax({
        type: 'post',
        url: 'http://127.0.0.1:3000/usertable',
        data: {
          UserId: _this.newUser.UserId,
          Avatarurl: _this.newUser.Avatarurl,
          UserName: _this.newUser.UserName,
          email: _this.newUser.email,
          IDcard: _this.newUser.IDcard,
          Phone: _this.newUser.Phone,
          Sex: '',
          RegisterTime: _this.newUser.RegisterTime,
          State: _this.newUser.State,
          password: _this.newUser.password,
        },
        success(res) {
          if (typeof res === 'object' && res !== null) {
            if (res.status === 200) {
              _this.fetchUsers(_this.currentPage, _this.pageSize, _this.searchQuery);
              _this.addDialogVisible = false;
              Message.success(`添加用户 ${_this.newUser.UserName} 成功`);
            } else {
              console.error('用户失败，服务器返回非成功状态:', res);
              Message.error(`用户失败，错误信息: ${res.msg || '未知错误'}`);
            }
          } else {
            console.error('用户失败，服务器响应格式错误:', res);
            Message.error('用户失败，服务器响应格式错误');
          }
        },
        error(err) {
          console.error('用户失败，请求发生错误:', err);
          Message.error('用户失败，请求发生错误');
        }
      });
    },
    // 生成新的用户ID
    generateNewId() {
      const maxId = this.users.reduce((max, user) => Math.max(max, user.UserId), 0);
      return maxId + 1;
    },
    // 状态返回对应的颜色
    getStateColor(State) {
      switch (State) {
        case '活跃':
          return '#E8F5E9';
        case '禁用':
          return '#FFE4E1';
        case '沉睡':
          return '#FFFFE0';
        case '流失':
          return '#F5F5F5';
        default:
          return 'transparent';
      }
    }, getStateTextColor(State) {
      switch (State) {
        case '活跃':
          return '#006400';
        case '禁用':
          return '#8B0000';
        case '沉睡':
          return '#B8860B';
        case '流失':
          return '#333333';
        default:
          return 'transparent';
      }
    },
    // 处理表格选中项变化
    handleSelectionChange(selectedUsers) {
      this.selectedUsers = selectedUsers;
    }
  },
  created() {
    this.totalUsers = this.users.length;
  }
};
</script>

<style lang="less" scoped>
.account {
  padding: 70px 20px 20px 230px;
  background-color: #F9FAFB;
  width: 100%;

  h2 {
    display: block;
    visibility: visible;
    margin-left: 10px;
  }

  .search-container {

    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    background-color: #ffffff;
    position: relative;
    margin: 20px 10px;
    width: 99%;


    .el-input {
      margin: 20px;
      width: 400px;
    }

    .el-button {
      padding: 10px 15px;
      border-radius: 8px;

      img {
        position: relative;
        top: 2px;
        width: 15px;
        height: 15px;
      }
    }

    .add {
      background-color: #007bff;
      color: white;
      position: absolute;
      top: 18px;
      right: 20px;
    }
  }
}
</style>